require 'will_paginate/array'
class SearchsController < ApplicationController
  layout 'search'
  def index
    if params[:kw].length>0 && params[:type].nil?
      @kw = params[:kw]
      searchs = User.find_by_sql('select d.id,d.projects as title,"demand" as s_type,d.created_at from demands as d where d.projects like "%'+@kw+'%" union all select q.id,q.title,"question" as s_type,q.created_at from questions q where q.title like "%'+@kw+'%" union all select u.id,u.name as title,"user" as s_type,u.created_at from users u where u.name like "%'+@kw+'%" order by created_at desc;')
      @total = searchs.count
      @searchs = searchs.paginate   :page=> params[:page],:per_page=> 12
    end
    if params[:kw].length>0 && !params[:type].nil?
      @kw = params[:kw]
      if params[:type] == 'user'
        searchs = User.find_by_sql('select u.id,u.name as title,"user" as s_type,u.created_at from users u where u.name like "%'+@kw+'%" order by created_at desc;')
      end
      if params[:type] == 'demand'
        searchs = User.find_by_sql('select d.id,d.projects as title,"demand" as s_type,d.created_at from demands as d where d.projects like "%'+@kw+'%"  order by created_at desc;')
      end
      if params[:type] == 'question'
        searchs = User.find_by_sql('select q.id,q.title,"question" as s_type,q.created_at from questions q where q.title like "%'+@kw+'%" order by created_at desc;')
      end
      @total = searchs.count
      @searchs = searchs.paginate   :page=> params[:page],:per_page=> 12
    end
  end
end
